﻿using System;
using NUnit.Framework;
using Rainbow.ObjectFlow.Framework;
using objectflow.core.tests.integration.TestOperations;
using Shouldly;

namespace objectflow.core.tests.integration
{
    public class ExceptionHandling 
    {
        // Static class creators
        [Test]
        public void Functions_should_throw_when_no_exception_policies()
        {
            Assert.Throws<Exception>(() => Workflow<string>.Definition().Do((x) => { throw new Exception(); }).Start());
        }

        [Test]
        public void Functions_should_handle_errors()
        {
            // TODO support static workflow helper
            //            Workflow<string>.Configure().On<Exception>(() => Console.WriteLine("caught exception")).When<string>().Do((x) => { throw new Exception(); });
        }

        // instance classes
        [Test]
        public void Instance_functions_should_throw_when_no_exception_policies()
        {
            var workflow = Workflow<string>.Definition();

            Assert.Throws<Exception>(()=> workflow.Do((x) => { throw new Exception(); }).Start());
        }

        [Test]
        public void Instance_functions_should_handle_exceptions()
        {
            var workflow = Workflow<string>.Definition();
            workflow.Configure().On<Exception>(() => Console.WriteLine("caught exception")).When<string>().Do((x) => { throw new Exception(); }).Start();
        }

        // operations
        [Test]
        public void Instance_operation_should_handle_exceptions()
        {
            var workflow = Workflow<string>.Definition();
            workflow.Configure().On<Exception>(() => Console.WriteLine("caught")).When<string>().Do<ExceptionOperation>().Start();
        }

        [Test]
        public void Instance_operation_should_throw_exceptions()
        {
            var workflow = Workflow<string>.Definition();
            Assert.Throws<Exception>(()=> workflow.Configure().When<string>().Do(new ExceptionOperation()).Start());
        }

        [Test]
        public void Should_run_functions_when_no_exceptions()
        {
            var result = Workflow<string>.Definition().Configure().On<Exception>(() => Console.WriteLine("caught")).When<string>().Do
                ((s) => s+"red").Start("red");

            result.ShouldBe("redred");
        }
    }
}